package com.example.demo.web.controller;

import com.example.demo.domain.User;
import com.example.demo.query.UserQuery;
import com.example.demo.service.IUserService;
import com.example.demo.util.AjaxResult;
import com.example.demo.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/user/index")
    public String index(Model model){
        //用户首页
        return "views/user/user_list";
    }

    @RequestMapping("/user/listpage")
    @ResponseBody
    public PageList listpage(UserQuery userQuery){
        System.out.println("传递参数:"+userQuery);
        //用户首页
        //List<User> userList = userService.queryAll();
        return  userService.listpage(userQuery);
    }

    //添加用户
    @RequestMapping("/user/addUser")
    @PreAuthorize("hasRole('砖石会员')")
    @ResponseBody
    public int addUser(User user){
        System.out.println("保存用户...."+user);
        userService.addUser(user);
        Integer userid = Integer.parseInt(user.getId()+"");
        //添加成功返回用户id
        return userid;
    }

    //修改用户editSaveUser
    @RequestMapping("/user/editSaveUser")
    @ResponseBody
    public AjaxResult editSaveUser(User user){
        System.out.println("修改用户...."+user);
        try {
            userService.editSaveUser(user);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxResult("修改失败");
    }

    //添加用户
    @RequestMapping("/user/deleteUser")
    @ResponseBody
    public AjaxResult deleteUser(Long id){
        System.out.println("删除用户...."+id);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            userService.deleteUser(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult("删除失败");
        }

        return ajaxResult;
    }

    @RequestMapping(value="/user/deleteBatchUser")
    @PreAuthorize("hasRole('砖石会员')")
    @ResponseBody
    public AjaxResult deleteBatchUser(String ids){
        System.out.println("批量删除用户...."+ids);

        String[] idsArr = ids.split(",");
        List list = new ArrayList();
        for(int i=0;i<idsArr.length;i++){
            list.add(idsArr[i]);
        }
        try{
            userService.batchRemove(list);
            return new AjaxResult();
        }catch(Exception e){
           return new AjaxResult("批量删除失败");
        }
    }
}
